<template>
  <div class="bind_container">
    <nut-form label-position="top" ref="formRef" :model-value="formData" :rules="rules">
      <nut-form-item :label="t('home_page_phone_number')" prop="mobile">
        <div class="code_wrap">
          <nut-input v-model="formData.mobile" :placeholder="t('home_page_inputPhone')"
            :disabled="userInfo.mobile != ''" type="text">
            <template #left>
              <div class="area_code">
                <span>+{{ formData.codeValue }}</span>
                <iconpark-icon color="#A8A8CA" icon-id="xia" size="1rem" class="mr-4"></iconpark-icon>
              </div>
            </template>
          </nut-input>
          <nut-button class="send_code" @click="sendCode">{{ codeValue }}</nut-button>
        </div>
      </nut-form-item>
      <nut-form-item :label="t('home_page_smsCode')" prop="verify_code">
        <nut-input v-model="formData.verify_code" :placeholder="t('home_page_enterSmsCode')" type="text" />
      </nut-form-item>
    </nut-form>
    <div :class="['submit_wrap',verifyTrue? '':'submit_wrap_1']">
      <nut-button class="submit" @click="submit"> {{ t("btn_label_next") }}</nut-button>
    </div>

    <Modal v-model:visible="SMSModal" :title="t('home_page_smsTitle')">
      <div class="tips">
        <p>
          {{ t("home_page_smsContent") }}<b>{{ t("home_page_smsPrice") }}</b>{{ t("home_page_smsContent1") }}
        </p>
        <div>
          {{ t("home_page_smsContent2") }}
          <!-- <span @click="router.push('/myWallet')">{{ t("home_page_smsGoWallet") }}</span> -->
          <span @click="router.push('/deposit')" style="color:#E43939;margin-left:3px"> {{ t("home_page_smsContent3") }}</span>
        </div>
        <nut-button class="btn_block" :bordered="false" block @click="sendMobileSmsCode">
          {{ t("btn_label_submit") }}</nut-button>
      </div>
    </Modal>
    <Toast v-model:visible="visible">{{ toast_value }}</Toast>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { verifyMobile } from "@/utils/validateTools";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { NetPacket } from "@/netBase/NetPacket";
import PKwebsocket from "@/lolo/Ws";
import { IP } from "@/utils/useStoreMethods";
import { User } from "@/store/user";
import pinia from "@/store";
import { storeToRefs } from "pinia";
const UserStore = User(pinia);
import { aaa, bbb, getDeviceId, getRandomSign } from "@/net/Utils";

const emits = defineEmits(["verifyClick"]);

const props = defineProps({
  verifyTrue: {
    type: Boolean,
    default: false,
  },
});

const { info: userInfo, roleInfo } = storeToRefs(UserStore);
const SMSModal = ref(false);
const router = useRouter();
const visible = ref(false);
const toast_value = ref("");
const { t } = useI18n();
const formRef: any = ref(null);
const codeValue = ref(t('get_verification_code'));
const times = ref(60);
const formData: any = ref({
  mobile: userInfo.value.mobile?.slice(2) || "",
  verify_code: "",
  codeValue: "84",
});

const mobileValidator = (value: string) => {
  if (!value) {
    return Promise.reject(t("home_page_enterPhoneNumber"));
  } else if (verifyMobile(formData.value.codeValue, value)) {
    return Promise.resolve();
  } else {
    return Promise.reject(t("home_page_phoneNumberFormatIncorrect"));
  }
};
const rules = {
  mobile: [{ validator: mobileValidator }],
};

const submit = () => {
  if (!formData.value.verify_code.trim()) {
    visible.value = true;
    toast_value.value = t("home_page_enterVerificationCode");
    return
  }
  formRef.value?.validate().then(async ({ valid, errors }: any) => {
    if (valid) {
      // 修改密码
      if (props.verifyTrue) {
        emits("verifyClick", formData.value);
      } else {
        // 绑定密码
        const id = await getDeviceId();
        const query: any = NetPacket.req_bind_modify_email();
        query.email = formData.value.codeValue + formData.value.mobile;
        query.operate_type = 3;
        query.captcha = formData.value.verify_code;
        query.aaa = aaa;
        query.bbb = bbb;
        query.sign = getRandomSign(id);
        query.ip = await IP();
        query.ip_error = "0";
        query.password = "";
        query.device_model = "";
        query.channel_id = 0;
        query.username = userInfo.value?.full_name;
        query.agent_id = roleInfo.value.id;
        PKwebsocket.instance.send(query, true, {
          callbackName: 'msg_notify_bind_modify_email',
          callback: notify_bind_result
        })
      }
    } else {
      console.warn("error:", errors);
    }
  });
};
const sendCode = () => {
  if (!formData.value.mobile) {
    visible.value = true;
    toast_value.value = t("home_page_enterPhoneNumber");
    return;
  }

  if (times.value < 60) {
    return;
  }
  if (verifyMobile(formData.value.codeValue, formData.value.mobile)) {
    SMSModal.value = true;
  } else {
    visible.value = true;
    toast_value.value = t("home_page_phoneNumberFormatIncorrect");
  }
};

// 手机验证码协议
const sendMobileSmsCode = () => {
  SMSModal.value = false;
  const req = NetPacket.req_get_mobile_sms_code();
  req.mobile = formData.value.codeValue + formData.value.mobile;
  req.operate_type = props.verifyTrue ? 3 : 1;
  PKwebsocket.instance.send(req, true, {
    callbackName: 'msg_notify_get_mobile_sms_code',
    callback: notify_result
  })
};

// 验证码回执

const notify_result = (rs: any) => {
  if (rs.code == 1) {
    visible.value = true;
    toast_value.value = t('verification_code_sent_success')
    let timeInterval = setInterval(() => {
      times.value--;
      codeValue.value = String(times.value);
      if (times.value <= 0) {
        clearInterval(timeInterval);
        codeValue.value = t('get_verification_code')
        times.value = 60;
      }
    }, 1000);
  } else {
    visible.value = true;
    toast_value.value = t(rs.message)
  }
};
// 提交回执
const notify_bind_result = (rs: any) => {
  if (rs.code == 1) {
    visible.value = true;
    toast_value.value = t('phone_tip_3')
    let req_user_info = NetPacket.req_user_info();
    setTimeout(() => {
      router.push("/securitySettings");
    }, 1500);
    PKwebsocket.instance.send(req_user_info, true)
  }else{
    visible.value = true;
    toast_value.value = t(rs.message)
  }
};

</script>

<style lang="scss" scoped>
@import url(../style.scss);

.area_code {
  display: flex;
  align-items: center;
  color: #ffffff;
  font-size: 14px;
  gap: 6px;
}

.tips {
  color: #ffffff;
  text-align: start;
  padding: 15px 10px 40px;
  

  p {
    padding-bottom: 15px;

    >b {
      color: #ED8302;
    }

    >span {
      color: red;
      cursor: pointer;
    }
  }
}
.btn_block{
  margin-top: 24px;
}
.submit_wrap_1{
  bottom: 50px !important;
  left: 0;
}
</style>
